<template>
  <div class="chart-wrapper2" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'GoodCharts',
  props: {
    xData: {
      type: Array,
      required: true
    },
    seriesData: {
      type: Array, // [{name: '真空合格率', data: [40,40,40,40,40,40,40]}, ...]
      required: true
    },
    // 传入结构与 seriesData 一致：[{ name: 'A线', data: [...] }, ...]
    // 每条产线各自的合格率曲线
    lineSeriesRateData: {
      type: Array,
      default: () => []
    },
    // 每条产线各自的合格数曲线
    lineSeriesQtyData: {
      type: Array,
      default: () => []
    },
    showDualAxis: {
      type: Boolean,
      default: false
    },
    qualifiedData: {
      type: Array, // [100, 200, 150, ...]
      default: () => []
    },
    qualificationRateData: {
      type: Array, // [90, 85, 92, ...]
      default: () => []
    },
    // 是否绘制两条全局折线（合格数/合格率）
    showGlobalLines: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    this.initChart();
  },
  watch: {
    xData: 'initChart',
    seriesData: 'initChart',
    showDualAxis: 'initChart',
    lineSeriesRateData: 'initChart',
    lineSeriesQtyData: 'initChart',
    qualifiedData: 'initChart',
    qualificationRateData: 'initChart'
  },
  methods: {
    initChart() {
      if (!this.$refs.chartRef) return;
      if (this.chart) this.chart.dispose();
      this.chart = echarts.init(this.$refs.chartRef);

      // 固定配色，顺序：真空、冷媒、商检、静音
      const colorList = ['#6b7cff', '#d6c96b', '#ffb21a', '#a18fff'];
      
      // 准备图例数据
      const legendData = [...this.seriesData.map(s => s.name)];
      // 计算柱子数据的最大值，用于左轴与曲线缩放
      const barAllValues = this.seriesData.reduce((arr, s) => arr.concat(s.data || []), []);
      const rawBarMax = Math.max(10, ...barAllValues);
      // 让刻度更好看，向上取整到10的倍数
      const leftAxisMax = Math.ceil(rawBarMax / 10) * 10;

      const series = this.seriesData.map((s, i) => ({
        ...s,
        type: 'bar',
        barWidth: 16,
        z: 2, // 保证柱子在前面
        itemStyle: { color: colorList[i % colorList.length] }
      }));
      
      // 仅渲染两条总线（合格数、合格率）
      if (this.showDualAxis && this.showGlobalLines && this.qualifiedData.length && this.qualificationRateData.length) {
        // 兼容旧的两个数组用法（两条线）
        // 将曲线缩放到左轴范围，使其与柱子高度量级接近
        const qMax = Math.max(...this.qualifiedData);
        const qFactor = qMax > 0 ? (leftAxisMax / qMax) : 1; // 合格数缩放系数
        const rFactor = leftAxisMax / 100; // 合格率缩放系数（0~100 对应 0~leftAxisMax）

        // 添加合格数曲线（左轴，数据已缩放）
        series.push({
          name: '合格数',
          type: 'line',
          yAxisIndex: 0,
          data: this.qualifiedData.map(v => +(v * qFactor).toFixed(2)),
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: { color: '#ff6b6b', width: 3 },
          itemStyle: { color: '#ff6b6b' },
          z: 1, // 在柱子后面
          // 自定义encode用于tooltip中还原原值
          __scaleFactor: qFactor
        });
        
        // 添加合格率曲线（左轴显示，右轴仅作刻度展示；数据已缩放）
        series.push({
          name: '合格率',
          type: 'line',
          yAxisIndex: 0,
          data: this.qualificationRateData.map(v => +(v * rFactor).toFixed(2)),
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: { color: '#64d2ff', width: 3 },
          itemStyle: { color: '#64d2ff' },
          z: 1,
          __scaleFactor: rFactor
        });
        
        legendData.push('合格数', '合格率');
      }

      const isLineSeriesMode = this.showDualAxis;

      const option = {
        backgroundColor: 'transparent',
        grid: {
          left: 0,
          right: this.showDualAxis ? 40 : 0,
          top: 40,
          bottom: 20,
          containLabel: true
        },
        title: {
          text: this.showDualAxis ? '不良分析' : '各工站良品率(%)',
          left: 0,
          top: 0,
          textStyle: {
            color: '#888ca0',
            fontSize: 14,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' },
          formatter: (params) => {
            const idx = params && params.length ? params[0].dataIndex : 0;
            let result = `${params[0].axisValue}<br/>`;

            // 收集当前刻度下的柱子数值（产量/数量）
            const barMap = {};
            params.forEach(p => {
              if (p.seriesType === 'bar') {
                barMap[p.seriesName] = p.value;
              }
            });

            // 帮助函数：从 per-line 数据取该刻度的值
            const pick = (arr, name) => {
              if (!arr || !arr.length) return undefined;
              const it = arr.find(x => x && x.name === name);
              if (!it || !Array.isArray(it.data)) return undefined;
              return it.data[idx];
            };

            // 按 seriesData 的顺序输出 ABCD
            (this.seriesData || []).forEach((s, i) => {
              const name = s.name;
              const color = ['#6b7cff', '#d6c96b', '#ffb21a', '#a18fff'][i % 4];
              const marker = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`;
              const qty = barMap[name];
              const rate = pick(this.lineSeriesRateData, name);
              const goodQty = pick(this.lineSeriesQtyData, name);
              const qtyText = (typeof qty !== 'undefined') ? qty : '-';
              const rateText = (typeof rate !== 'undefined') ? `${rate}%` : '-';
              const goodQtyText = (typeof goodQty !== 'undefined') ? `${goodQty}` : '-';
              result += `${marker}${name}: 产量 ${qtyText}，合格率 ${rateText}，合格数 ${goodQtyText}<br/>`;
            });

            // 追加底部两条总线原值（若存在且开启显示）
            if (this.showGlobalLines) {
              const lineVals = [];
              params.forEach(p => {
                if (p.seriesType === 'line') {
                  const scale = (typeof p.seriesIndex === 'number' && option && option.series)
                    ? (option.series[p.seriesIndex] || {}).__scaleFactor
                    : undefined;
                  const rawValue = scale ? +(p.value / scale).toFixed(2) : p.value;
                  const unit = p.seriesName.includes('合格率') ? '%' : '';
                  lineVals.push(`${p.seriesName}: ${rawValue}${unit}`);
                }
              });
              if (lineVals.length) {
                result += lineVals.map(v => `${v}`).join('<br/>');
              }
            }
            return result;
          }
        },
        legend: {
          data: legendData,
          right: 10,
          top: 0,
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            color: '#888ca0',
            fontSize: 14
          }
        },
        xAxis: {
          type: 'category',
          data: this.xData,
          axisLine: { lineStyle: { color: '#888ca0' } },
          axisLabel: { color: '#888ca0', fontSize: 14 },
          axisTick: { show: false }
        },
        yAxis: [
          // 左轴
          {
            type: 'value',
            min: 0,
            max: this.showDualAxis ? leftAxisMax : 100,
            interval: this.showDualAxis ? Math.ceil(leftAxisMax / 5) : 20,
            axisLine: { show: false },
            axisLabel: {
              color: '#888ca0',
              fontSize: 14,
              formatter: (value) => this.showDualAxis ? value : `${value}%`
            },
            splitLine: { lineStyle: { color: '#333' } }
          },
          // 右轴（仅在双轴模式下显示）
          ...(this.showDualAxis ? [{
            type: 'value',
            min: 0,
            max: 100,
            interval: 20,
            position: 'right',
            axisLine: { show: true, lineStyle: { color: '#64d2ff' } },
            axisLabel: {
              color: '#64d2ff',
              fontSize: 14,
              formatter: '{value}%'
            },
            splitLine: { show: false }
          }] : [])
        ],
        // 为了在 tooltip 中能获取缩放系数，给每个系列一个 id 并挂载自定义属性
        series: series.map((s, idx) => ({ id: `s${idx}`, ...s }))
      };
      
      this.chart.setOption(option);
    }
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose();
  }
};
</script>

<style scoped>
.chart-wrapper2 {
  width: 100%;
  height: 220px;
  background: transparent;
}
</style>
